package com.nuedu.corejava.ch12;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class MyFileReader {
	/**
	 * 
	 * 拷贝文件，并把小写l全部修改为大写L
	 * 
	 * @param src
	 * @param desc
	 */
	public void copyAndFilete(String src, String desc) {
		if (src == null || desc == null) {
			return;
		}
		File srcFile = new File(src);
		File descFile = new File(desc);

		if (!srcFile.exists()) {
			return;
		}
		FileReader reader = null;
		FileWriter writer = null;
		BufferedReader bufferedReader = null;

		try {
			descFile.createNewFile();

			if (!descFile.exists()) {
				descFile.getParentFile().mkdirs();
			}
			reader = new FileReader(srcFile);
			bufferedReader = new BufferedReader(reader);
			writer = new FileWriter(descFile);

			String data = null;
			// readLine一次读取一行内容，文件读取完毕返回null；
			while ((data = bufferedReader.readLine()) != null) {
				String newDtata = data.replaceAll("l", "L");
				writer.write(newDtata);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 把一段文本内容写入到指定文件中
	 * 
	 * @param fileName
	 * @param content
	 */
	public void writeFile(String fileName, String content) {
		if (fileName == null) {
			return;
		}
		File file = new File(fileName);
		FileOutputStream outputStream = null;
		try {
			if (file.exists()) {
				file.getParentFile().mkdirs();
				file.createNewFile();
			}
			outputStream = new FileOutputStream(file, false);// 文件的写入有两种模式，false - 覆盖重写，ture - 追加；
			outputStream.write(content.getBytes());// 需要把字符串转换成字节数组；转换时需要注意可能产生乱码；
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public static void main(String[] args) {
		String filString = "c:\\test.txt";
		String contenString = "Hello Word!";
		MyFileReader fileWriter = new MyFileReader();
		fileWriter.writeFile(filString, contenString);
		System.out.println("文件新增成功！");
		fileWriter.copyAndFilete("c:\\test.txt", "c:\\test2.txt");
	}

}
